//
//  PlayingViewController.m
//  storyTest
//
//  Created by 史沐卉 on 2018/12/4.
//  Copyright © 2018 Facebook. All rights reserved.
//

#import "PlayingViewController.h"
#import <MediaPlayer/MediaPlayer.h>
#import <notify.h>
#import <UIKit/UIKit.h>
#import <AVFoundation/AVFoundation.h>

#define SONGNAME @"多幸运"

@interface PlayingViewController ()
@property (nonatomic, strong) AVAudioPlayer * player;
@end
@implementation PlayingViewController
RCT_EXPORT_MODULE();

RCT_EXPORT_METHOD(viewDidLoad) {
//  [super viewDidLoad];
  NSLog(@"开始");
  [self.player play];
  
//  [self playControl];

  //添加远程锁屏控制
//  [self createRemoteCommandCenter];
  
}

- (AVAudioPlayer *)player{
  NSLog(@"开始2");
  if (_player == nil) {
    NSURL *url = [[NSBundle mainBundle] URLForResource:@"./多幸运.mp3" withExtension:nil];
    _player = [[AVAudioPlayer alloc] initWithContentsOfURL:url error:nil];
  }
  return _player;
}

//播放控制和监测
- (void)playControl{
  NSLog(@"开始3");
  //后台播放音频设置,需要在Capabilities->Background Modes中勾选Audio,Airplay,and Picture in Picture
  AVAudioSession *session = [AVAudioSession sharedInstance];
  
  [session setCategory:AVAudioSessionCategoryPlayback error:nil];
  
  [session setActive:YES error:nil];
  
  //展示锁屏歌曲信息，上面监听屏幕锁屏和点亮状态的目的是为了提高效率
  [self showLockScreenTotaltime];
  
}

//展示锁屏歌曲信息：图片、歌词、进度、演唱者 播放速率
- (void)showLockScreenTotaltime{
  NSLog(@"开始4");
  NSMutableDictionary * songDict = [[NSMutableDictionary alloc] init];
  //设置歌曲题目
  [songDict setObject:@"多幸运" forKey:MPMediaItemPropertyTitle];
  //设置歌手名
  [songDict setObject:@"韩安旭" forKey:MPMediaItemPropertyArtist];
  //设置专辑名
  [songDict setObject:@"专辑名" forKey:MPMediaItemPropertyAlbumTitle];
  //设置歌曲时长
//  [songDict setObject:[NSNumber numberWithDouble:totalTime]  forKey:MPMediaItemPropertyPlaybackDuration];
//  //设置已经播放时长
//  [songDict setObject:[NSNumber numberWithDouble:currentTime] forKey:MPNowPlayingInfoPropertyElapsedPlaybackTime];
  //设置播放速率
  //注意：MPNowPlayingInfoCenter的rate 与 self.player.rate 是不同步的，也就是说[self.player pause]暂停播放后的速率rate是0，但MPNowPlayingInfoCenter的rate还是1，就会造成 在锁屏界面点击了暂停按钮，这个时候进度条表面看起来停止了走动，但是其实还是在计时，所以再点击播放的时候，锁屏界面进度条的光标会发生位置闪动， 所以我们需要在暂停或播放时保持播放速率一致
//  [songDict setObject:[NSNumber numberWithInteger:rate] forKey:MPNowPlayingInfoPropertyPlaybackRate];
  
//  UIImage * lrcImage = [UIImage imageNamed:@"backgroundImage5.jpg"];
//  //设置显示的海报图片
//  [songDict setObject:[[MPMediaItemArtwork alloc] initWithImage:lrcImage]
//               forKey:MPMediaItemPropertyArtwork];
  
  
  [[MPNowPlayingInfoCenter defaultCenter] setNowPlayingInfo:songDict];
  
}

/** 这个方法在开始播放音乐的时候手动调用 */
RCT_EXPORT_METHOD(setupLockScreenInfo:(NSString *)name singer:(NSString *)singer)
{
//  (NSString *)name singer:(NSString *)singer duration:(NSString *)duration currentTime:(NSString *)currentTime
  // 0.获取当前正在播放的歌曲
  //
  //  NSDictionary *playingMusic = @{name:@"那些花儿",
  //                        singer:@"朴树",
  //                        icon: @""
  //                        };
  
  // 1.获取锁屏界面中心
  MPNowPlayingInfoCenter *playingInfoCenter = [MPNowPlayingInfoCenter defaultCenter];
  
  // 2.设置展示的信息
  NSMutableDictionary *playingInfo = [NSMutableDictionary dictionary];
  // 设置歌曲标题
  [playingInfo setObject:name forKey:MPMediaItemPropertyAlbumTitle];
  // 设置歌手
  [playingInfo setObject:singer forKey:MPMediaItemPropertyArtist];
  // 设置封面
//    MPMediaItemArtwork *artWork = [[MPMediaItemArtwork alloc] initWithImage:[UIImage imageNamed:@""]];
//    [playingInfo setObject:artWork forKey:MPMediaItemPropertyArtwork];
  // 设置歌曲播放的总时长
//  [playingInfo setObject:duration forKey:MPMediaItemPropertyPlaybackDuration];
//  // 设置已经播放时长
//  [playingInfo setObject:currentTime forKey:MPNowPlayingInfoPropertyElapsedPlaybackTime];

  playingInfoCenter.nowPlayingInfo = playingInfo;
  
}

//-(BOOL)canBecomeFirstResponder{
//  return YES;
//}
///** 监听远程事件 */
//-(void)remoteControlReceivedWithEvent:(UIEvent *)event
//{
//  NSLog(@"remoteControlReceivedWithEvent");
//  switch (event.subtype) {
//    case UIEventSubtypeRemoteControlPlay: // 播放
//    case UIEventSubtypeRemoteControlStop: // 暂停
//      //      [self playOrPause]; // 控制播放与暂停
//      break;
//    case UIEventSubtypeRemoteControlNextTrack: // 下一首
//      //      [self next]; // 控制播放下一首
//
//      break;
//    case UIEventSubtypeRemoteControlPreviousTrack: // 上一首
//      //      [self previous]; // 控制播放上一首
//      break;
//    default:
//      break;
//  }
//}

//锁屏界面开启和监控远程控制事件
- (void)createRemoteCommandCenter{
  //RCT_EXPORT_METHOD(createRemoteCommandCenter:(RCTResponseSenderBlock) callback){
  /**/
  //远程控制命令中心 iOS 7.1 之后
  NSLog(@"createRemoteCommandCenter");
  
  MPRemoteCommandCenter *commandCenter = [MPRemoteCommandCenter sharedCommandCenter];
  
  //   MPFeedbackCommand对象反映了当前App所播放的反馈状态. MPRemoteCommandCenter对象提供feedback对象用于对媒体文件进行喜欢, 不喜欢, 标记的操作. 效果类似于网易云音乐锁屏时的效果
  [commandCenter.pauseCommand addTargetWithHandler:^MPRemoteCommandHandlerStatus(MPRemoteCommandEvent * _Nonnull event) {
    NSLog(@"暂停播放");
//    callback(@[@"暂停"]);
    return MPRemoteCommandHandlerStatusSuccess;
  }];
  
  [commandCenter.playCommand addTargetWithHandler:^MPRemoteCommandHandlerStatus(MPRemoteCommandEvent * _Nonnull event) {
    NSLog(@"继续播放");
//    callback(@[@"继续"]);
    return MPRemoteCommandHandlerStatusSuccess;
  }];
  
  [commandCenter.togglePlayPauseCommand addTargetWithHandler:^MPRemoteCommandHandlerStatus(MPRemoteCommandEvent * _Nonnull event) {
    NSLog(@"耳机");
    return MPRemoteCommandHandlerStatusSuccess;
  }];
  
  [commandCenter.nextTrackCommand addTargetWithHandler:^MPRemoteCommandHandlerStatus(MPRemoteCommandEvent * _Nonnull event) {
    NSLog(@"下一首");
    return MPRemoteCommandHandlerStatusSuccess;
  }];
  
  [commandCenter.previousTrackCommand addTargetWithHandler:^MPRemoteCommandHandlerStatus(MPRemoteCommandEvent * _Nonnull event) {
    NSLog(@"上一首");
    return MPRemoteCommandHandlerStatusSuccess;
  }];
  
  //在控制台拖动进度条调节进度（仿QQ音乐的效果）
  [commandCenter.changePlaybackPositionCommand addTargetWithHandler:^MPRemoteCommandHandlerStatus(MPRemoteCommandEvent * _Nonnull event) {
    MPChangePlaybackPositionCommandEvent * playbackPositionEvent = (MPChangePlaybackPositionCommandEvent *)event;
    NSLog(@"进度条");
    return MPRemoteCommandHandlerStatusSuccess;
  }];

  
}

@end
